﻿import kliment.controls.ControlsAbstract;
import kliment.display.MCC;
import mx.utils.Delegate;

/**
 * ...
 * @author	Kliment
 * @version	1.3.2
 */
class kliment.effect.Magnet extends ControlsAbstract{
	private var _elements:Array;
	private var _power:Number;
	private var _deviation:Number;
	private var _clocker:MovieClip;
	
	public function Magnet(objects:Object, power:Number, deviation:Number) {
		_power = power;
		_deviation = deviation;
		_clocker = MCC.create();
		_elements = new Array();
		for (var i in objects) {
			var item = objects[i];
			if (item instanceof MovieClip)
			addMovieClip(item);
		}
		_init();
	}
	
	private function _init():Void {
		enable = true;
	}
	
	public function set enable(value:Boolean):Void {
		if (value) {
			_clocker.onEnterFrame = Delegate.create(this, _move);
		} else {
			_clocker.onEnterFrame = null;
		}
		super.enable = value;
	}
	
	private function _move():Void {
		var i:Number = _elements.length;
		while (i--) {
			var item_mc:MovieClip = _elements[i];
			
			var xMouse:Number = item_mc._xmouse;
			var yMouse:Number = item_mc._ymouse;
			var distance:Number = Math.sqrt(xMouse * xMouse + yMouse * yMouse);
			var mx:Number = _power / distance;
			var powerX:Number = item_mc._x - xMouse / distance * mx;
			var powerY:Number = item_mc._y - yMouse / distance * mx;
			item_mc.forceX = (item_mc.forceX + (item_mc.startX - item_mc._x) * .5) / _deviation;
			item_mc.forceY = (item_mc.forceY + (item_mc.startY - item_mc._y) * .5) / _deviation;
			item_mc._x = powerX + item_mc.forceX;
			item_mc._y = powerY + item_mc.forceY;
		}
	}
	
	public function addMovieClip(target_mc:MovieClip):Void {
		target_mc.forceX = 0;
		target_mc.forceY = 0;
		target_mc.startX = target_mc._x;
		target_mc.startY = target_mc._y;
		_elements.push(target_mc);
	}
	
	public function remove():Void {
		MCC.remove(_clocker);
		delete this;
	}
}